// 监听来自 popup 的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === "showEdit") {
        showEditUI();
    } else if (request.action === "togglePlugin") {
        togglePlugin(request.enabled);
    }
});

// 插件启用状态
let isEnabled = true;

// 切换插件状态
function togglePlugin(enabled) {
    isEnabled = enabled;
    const panel = document.querySelector('.auto-fill-panel');
    if (panel) {
        if (enabled) {
            panel.style.display = '';
        } else {
            panel.style.display = 'none';
        }
    }
}

// 初始化时检查插件状态
chrome.storage.local.get(['enabled'], function(result) {
    isEnabled = result.enabled !== false;
    const panel = document.querySelector('.auto-fill-panel');
    if (panel && !isEnabled) {
        panel.style.display = 'none';
    }
});

// 默认用户数据结构
const defaultUserData = {
    categories: [
        {
            name: '基本信息',
            fields: [
                { label: '姓名', value: '张三' },
                { label: '性别', value: '男' },
                { label: '年龄', value: '28' },
                { label: '电话', value: '13800138000' },
                { label: '邮箱', value: 'zhangsan@example.com' }
            ]
        },
        {
            name: '教育经历',
            fields: [
                { label: '学校', value: '北京大学' },
                { label: '专业', value: '计算机科学' },
                { label: '学历', value: '本科' }
            ]
        }
    ]
};

// 获取用户数据
let userData = defaultUserData;
chrome.storage.local.get(['userData'], (result) => {
    if (result.userData) {
        userData = result.userData;
    } else {
        chrome.storage.local.set({ userData: defaultUserData });
    }
});

// 创建面板元素
function createPanel() {
    const panel = document.createElement('div');
    panel.className = 'auto-fill-panel';
    panel.innerHTML = `
        <div class="panel-title">
            <span>表单宝 <span style="font-size: 12px; color: #888; font-weight: normal; margin-left: 10px;">Design by abin</span></span>
            <span class="minimize-button" style="width: 30px; text-align: center;">⟪</span>
        </div>
        <div class="welcome-message">
            欢迎使用表单宝！👋<br>
            由 <span class="author">abin</span> 精心打造的填表助手<br>
            点击输入框即可快速填写信息。
            妈妈再也不用担心我填表了！
        </div>
        <div class="panel-content"></div>
        <div class="panel-footer">
            <button class="edit-button">编辑预设信息</button>
        </div>
    `;
    document.body.appendChild(panel);
    
    // 添加最小化按钮功能
    const minimizeButton = panel.querySelector('.minimize-button');
    minimizeButton.addEventListener('click', (e) => {
        e.stopPropagation(); // 阻止事件冒泡
        togglePanel(panel);
    });

    // 添加点击最小化状态时的展开功能
    panel.addEventListener('click', (e) => {
        if (panel.classList.contains('minimized')) {
            togglePanel(panel);
        }
    });
    
    // 添加底部编辑按钮功能
    const editButton = panel.querySelector('.edit-button');
    editButton.addEventListener('click', () => {
        showEditUI();
    });
    
    return panel;
}

// 切换面板展开/收起状态
function togglePanel(panel) {
    const isMinimized = panel.classList.toggle('minimized');
    const minimizeButton = panel.querySelector('.minimize-button');
    minimizeButton.textContent = isMinimized ? '⟫' : '⟪';
}

// 显示面板并显示与输入字段相关的项目
function showPanel(inputElement, panel) {
    // 确保面板可见
    if (panel.classList.contains('minimized')) {
        togglePanel(panel);
    }

    const panelContent = panel.querySelector('.panel-content');
    panelContent.innerHTML = '';
    
    // 获取输入上下文
    const inputId = (inputElement.id || '').toLowerCase();
    const inputName = (inputElement.name || '').toLowerCase();
    const inputPlaceholder = (inputElement.placeholder || '').toLowerCase();
    const inputLabel = getInputLabel(inputElement).toLowerCase();
    const combinedText = `${inputId} ${inputName} ${inputPlaceholder} ${inputLabel}`;
    
    let prioritizedItems = [];
    
    // 处理每个分类及其字段
    userData.categories.forEach(category => {
        let categoryItems = [];
        
        category.fields.forEach(field => {
            // 根据字段标签匹配计算优先级
            const priority = combinedText.includes(field.label.toLowerCase()) ? 10 : 0;
            
            categoryItems.push({
                label: `${field.label}: ${field.value}`,
                value: field.value,
                priority: priority
            });
        });
        
        // 仅当有项目时添加分类及其项目
        if (categoryItems.length > 0) {
            // 创建分类容器
            const categoryContainer = document.createElement('div');
            
            // 添加分类标题
            const categoryHeader = document.createElement('div');
            categoryHeader.className = 'panel-category collapsed';
            categoryHeader.textContent = category.name;
            categoryContainer.appendChild(categoryHeader);
            
            // 创建项目容器
            const itemsContainer = document.createElement('div');
            itemsContainer.className = 'panel-items-container collapsed';
            
            // 按优先级排序分类内的项目
            categoryItems.sort((a, b) => b.priority - a.priority);
            
            // 添加项目
            categoryItems.forEach((item, index) => {
                const itemElement = document.createElement('div');
                itemElement.className = 'panel-item';
                itemElement.textContent = item.label;
                itemElement.dataset.value = item.value;
                itemElement.dataset.index = prioritizedItems.length + index;
                
                itemElement.addEventListener('click', () => {
                    fillInputAndTriggerEvents(inputElement, item.value);
                });
                
                itemsContainer.appendChild(itemElement);
            });
            
            categoryContainer.appendChild(itemsContainer);
            panelContent.appendChild(categoryContainer);
            
            // 为分类标题添加点击处理程序
            categoryHeader.addEventListener('click', () => {
                const isCollapsed = categoryHeader.classList.toggle('collapsed');
                itemsContainer.classList.toggle('collapsed');
                
                // 设置初始高度以实现动画效果
                if (!isCollapsed) {
                    itemsContainer.style.height = itemsContainer.scrollHeight + 'px';
                }
            });
            
            // 设置初始高度
            requestAnimationFrame(() => {
                const height = itemsContainer.scrollHeight;
                itemsContainer.style.height = `${height}px`;
            });
            
            // 添加所有项目到优先级数组
            prioritizedItems = prioritizedItems.concat(categoryItems);
        }
    });
    
    // 如果没有添加任何项目，显示空消息
    if (prioritizedItems.length === 0) {
        panelContent.innerHTML = '<div class="panel-empty">暂无数据</div>';
    }
    
    // 存储当前输入的引用
    panel.currentInput = inputElement;
    
    // 设置第一个项目为选中状态
    if (prioritizedItems.length > 0) {
        const firstItem = panel.querySelector('.panel-item');
        if (firstItem) {
            firstItem.classList.add('selected');
        }
    }
}

// 获取输入字段的标签文本的辅助函数
function getInputLabel(inputElement) {
    // Try to find a label that references the input by id
    if (inputElement.id) {
        const label = document.querySelector(`label[for="${inputElement.id}"]`);
        if (label) {
            return label.textContent || '';
        }
    }
    
    // Try to find a parent label
    let parent = inputElement.parentElement;
    while (parent) {
        if (parent.tagName === 'LABEL') {
            return parent.textContent || '';
        }
        
        // Look for label-like elements nearby
        const nearbyLabels = parent.querySelectorAll('label, .label, .field-label, .form-label');
        for (let i = 0; i < nearbyLabels.length; i++) {
            if (nearbyLabels[i].textContent) {
                return nearbyLabels[i].textContent;
            }
        }
        
        parent = parent.parentElement;
    }
    
    return '';
}

// 填充输入字段并触发必要的事件
function fillInputAndTriggerEvents(inputElement, value) {
    inputElement.value = value;
    
    // Trigger events to notify the page of the change
    ['input', 'change'].forEach(eventType => {
        const event = new Event(eventType, { bubbles: true });
        inputElement.dispatchEvent(event);
    });
}

// 创建并显示编辑界面
function showEditUI() {
    const modal = document.createElement('div');
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10000;
        font-family: Arial, sans-serif;
    `;
    
    const modalContent = document.createElement('div');
    modalContent.style.cssText = `
        background: white;
        border-radius: 8px;
        padding: 20px;
        width: 80%;
        max-width: 800px;
        max-height: 80vh;
        overflow-y: auto;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
        position: relative;
    `;
    
    // Get current data
    chrome.storage.local.get(['userData'], (result) => {
        const currentData = result.userData || defaultUserData;
        
        // Create category management interface
        modalContent.innerHTML = `
            <h2 style="margin-top: 0; color: #333;">表单宝 - 编辑个人信息 <span style="font-size: 12px; color: #888; font-weight: normal; margin-left: 10px;">Design by abin</span></h2>
            <div class="edit-tips" style="margin-bottom: 15px; padding: 8px; background: #f8f9fa; border-radius: 4px; font-size: 13px;">
                <div style="color: #0d6efd;">● 分类名称 - 用于组织和管理相关字段</div>
                <div style="color: #198754;">● 字段标签 - 用于匹配输入框</div>
                <div style="color: #dc3545;">● 字段内容 - 实际填充的值</div>
            </div>
            <div id="categories-container">
                ${currentData.categories.map((category, categoryIndex) => `
                    <div class="category-item" style="margin-bottom: 20px; border: 1px solid #eee; padding: 15px; border-radius: 4px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <input type="text" class="category-name" value="${category.name}" 
                                style="font-size: 16px; font-weight: bold; border: none; background: transparent; color: #0d6efd;">
                            <button class="remove-category-btn" data-index="${categoryIndex}"
                                style="padding: 5px 10px; background: #f44336; color: white; border: none; border-radius: 4px; cursor: pointer;">
                                删除分类
                            </button>
                        </div>
                        <div class="fields-container">
                            ${category.fields.map((field, fieldIndex) => `
                                <div class="field-item" style="display: flex; gap: 10px; margin-bottom: 10px;">
                                    <input type="text" class="field-label" value="${field.label}" placeholder="字段名称"
                                        style="flex: 1; padding: 8px; border: 1px solid #198754; border-radius: 4px; color: #198754;">
                                    <input type="text" class="field-value" value="${field.value}" placeholder="字段值"
                                        style="flex: 2; padding: 8px; border: 1px solid #dc3545; border-radius: 4px; color: #dc3545;">
                                    <button class="remove-field-btn" data-category="${categoryIndex}" data-field="${fieldIndex}"
                                        style="padding: 5px 10px; background: #f44336; color: white; border: none; border-radius: 4px; cursor: pointer;">
                                        删除
                                    </button>
                                </div>
                            `).join('')}
                        </div>
                        <button class="add-field-btn" data-category="${categoryIndex}"
                            style="margin-top: 10px; padding: 8px 15px; background: #4caf50; color: white; border: none; border-radius: 4px; cursor: pointer;">
                            添加字段
                        </button>
                    </div>
                `).join('')}
            </div>
            <button id="add-category" 
                style="width: 100%; padding: 10px; margin: 10px 0; background: #2196f3; color: white; border: none; border-radius: 4px; cursor: pointer;">
                添加新分类
            </button>
            <div style="margin-top: 20px; text-align: right;">
                <button id="reset-default" 
                    style="float: left; padding: 8px 15px; background: #ff9800; color: white; border: none; border-radius: 4px; cursor: pointer;">
                    恢复默认设置
                </button>
                <button id="cancel-edit" 
                    style="margin-right: 10px; padding: 8px 15px; background: #f5f5f5; border: 1px solid #ccc; border-radius: 4px; cursor: pointer;">
                    取消
                </button>
                <button id="save-edit" 
                    style="padding: 8px 15px; background: #4285f4; color: white; border: none; border-radius: 4px; cursor: pointer;">
                    保存
                </button>
            </div>
        `;
        
        modal.appendChild(modalContent);
        document.body.appendChild(modal);
        
        // Add event listeners
        // Add new category
        document.getElementById('add-category').addEventListener('click', () => {
            const categoriesContainer = document.getElementById('categories-container');
            const newCategoryIndex = document.querySelectorAll('.category-item').length;
            
            const newCategory = document.createElement('div');
            newCategory.className = 'category-item';
            newCategory.style.cssText = 'margin-bottom: 20px; border: 1px solid #eee; padding: 15px; border-radius: 4px;';
            
            newCategory.innerHTML = `
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                    <input type="text" class="category-name" value="新分类" 
                        style="font-size: 16px; font-weight: bold; border: none; background: transparent; color: #0d6efd;">
                    <button class="remove-category-btn" data-index="${newCategoryIndex}"
                        style="padding: 5px 10px; background: #f44336; color: white; border: none; border-radius: 4px; cursor: pointer;">
                        删除分类
                    </button>
                </div>
                <div class="fields-container"></div>
                <button class="add-field-btn" data-category="${newCategoryIndex}"
                    style="margin-top: 10px; padding: 8px 15px; background: #4caf50; color: white; border: none; border-radius: 4px; cursor: pointer;">
                    添加字段
                </button>
            `;
            
            categoriesContainer.appendChild(newCategory);
            setupEventListeners(newCategory);
        });
        
        // Setup event listeners for dynamic elements
        function setupEventListeners(container) {
            // Add field button
            container.querySelector('.add-field-btn')?.addEventListener('click', function() {
                const fieldsContainer = this.previousElementSibling;
                const newField = document.createElement('div');
                newField.className = 'field-item';
                newField.style.cssText = 'display: flex; gap: 10px; margin-bottom: 10px;';
                
                newField.innerHTML = `
                    <input type="text" class="field-label" placeholder="字段名称"
                        style="flex: 1; padding: 8px; border: 1px solid #198754; border-radius: 4px; color: #198754;">
                    <input type="text" class="field-value" placeholder="字段值"
                        style="flex: 2; padding: 8px; border: 1px solid #dc3545; border-radius: 4px; color: #dc3545;">
                    <button class="remove-field-btn"
                        style="padding: 5px 10px; background: #f44336; color: white; border: none; border-radius: 4px; cursor: pointer;">
                        删除
                    </button>
                `;
                
                fieldsContainer.appendChild(newField);
                
                // Add remove field button listener
                newField.querySelector('.remove-field-btn').addEventListener('click', function() {
                    newField.remove();
                });
            });
            
            // Remove category button
            container.querySelector('.remove-category-btn')?.addEventListener('click', function() {
                container.remove();
            });
            
            // Remove field buttons
            container.querySelectorAll('.remove-field-btn').forEach(button => {
                button.addEventListener('click', function() {
                    this.closest('.field-item').remove();
                });
            });
        }
        
        // Setup initial event listeners
        document.querySelectorAll('.category-item').forEach(setupEventListeners);
        
        // Cancel button
        document.getElementById('cancel-edit').addEventListener('click', () => {
            document.body.removeChild(modal);
        });
        
        // Reset to default
        document.getElementById('reset-default').addEventListener('click', () => {
            if (confirm('确定要恢复默认设置吗？这将覆盖您当前的所有数据。')) {
                chrome.storage.local.set({ userData: defaultUserData }, () => {
                    userData = defaultUserData;
                    alert('已恢复默认设置，请重新打开编辑窗口查看。');
                    document.body.removeChild(modal);
                });
            }
        });
        
        // Save button
        document.getElementById('save-edit').addEventListener('click', () => {
            try {
                const newData = {
                    categories: []
                };
                
                // Gather all categories and their fields
                document.querySelectorAll('.category-item').forEach(categoryElem => {
                    const category = {
                        name: categoryElem.querySelector('.category-name').value,
                        fields: []
                    };
                    
                    categoryElem.querySelectorAll('.field-item').forEach(fieldElem => {
                        category.fields.push({
                            label: fieldElem.querySelector('.field-label').value,
                            value: fieldElem.querySelector('.field-value').value
                        });
                    });
                    
                    newData.categories.push(category);
                });
                
                chrome.storage.local.set({ userData: newData }, () => {
                    userData = newData;
                    alert('数据保存成功！');
                    document.body.removeChild(modal);
                });
            } catch (e) {
                alert('保存失败: ' + e.message);
            }
        });
    });
}

// 初始化脚本
function init() {
    const panel = createPanel();
    
    // Setup input detection
    document.addEventListener('focusin', (event) => {
        if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
            showPanel(event.target, panel);
        }
    });
}

// 立即运行初始化
init(); 